package com.rocky_tech.framework.struts.action;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.rocky_tech.biz.DecideAction;
import com.rocky_tech.framework.struts.form.ActionForm;
import com.rocky_tech.framework.struts.form.FullForm;
import com.rocky_tech.framework.xmlprase.XmlBean;

/**
 * @author zzc
 * @time 2017-07-25
 */ 
@WebServlet("*.do")
public class ActionServlet extends HttpServlet{
	
	
	private static final long serialVersionUID = 1L;

	@Override
	public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		// 设置页面编码
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		// 获得页面请求访问servlet的路径(demo中是index.jsp是"/decide"),这个路径和struts-config.xml中<action-mapping>下<action>标签的"path"属性对应，这个属性值必须唯一。
		String servletPath = request.getServletPath();
		// 获得请求头
		String path = this.getPath(servletPath);
		//System.out.println(path);
		// 获得监听器内容，也就是通过监听器协解析过后，得到"Struts-config.xml"文件解析过后的类
		Map<String ,XmlBean> map = (Map<String ,XmlBean>)this.getServletContext().getAttribute("struts");
		//通过"path"当key值，得到此次请求需要反射的form类和业务action类的信息
		XmlBean xml = map.get(path);
		String formClass = xml.getFormClass();
		//通过反射，实例化form类
		ActionForm form  = FullForm.full(formClass,request);
		String actionClass = xml.getActionClass();
		Action action = null;
		String url = "";
		try{
			//	实例化要做具体业务的action类，这里的接口Aciton类（demo只返回要跳转的为String类型的url）
			Class clazz = Class.forName(actionClass);
			action = (Action)clazz.newInstance();
			url = action.execute(request, response,form, xml.getActionForward());
			System.out.println("url="+url);
		}catch(Exception e){
			e.printStackTrace();
			System.out.println("严重：控制器异常！");
			
		}
		//  获得了转发器对象
		// 转发器只需要一个字符串对象进行转发
		RequestDispatcher dis = request.getRequestDispatcher(url);
		dis.forward(request, response);
	}
	
	@Override
	public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		this.doPost(request, response);
	}
	
	
	//根据获得请求的servlet路径，得出struts-config.xml中的"path"
	private  String getPath(String servletPath){
		return servletPath.split("\\.")[0];
	}
}
